﻿using System;
using System.Xml.Linq;

namespace SharePoint.Orm.Caml {
	///<summary>
	/// This creates a where clause in the Caml Query. 
	///</summary>
	/// <example>
	/// <code>
	/// CamlWhere where = new CamlWhere {
	///			Root = new CamlEquals {
	///				FieldRef = new CamlFieldRef("Make"),
	///				Value = new CamlValue(CamlValueType.String, "Porsche")
	///			}
	///		};
	/// </code>
	/// </example>
	public class CamlWhere {
		/// <summary>
		/// The root of the entire expression. Append other CamlExpr to this.
		/// </summary>
		public CamlExpr Root { get; set; }

		public void AppendWhere(CamlExpr camlExpr, CamlLogicalOpType op) {
			Root = Root == null ? camlExpr : new CamlLogicalOp(op, Root, camlExpr);
		}

		public void AppendWhere(CamlExpr camlExpr) {
			AppendWhere(camlExpr, CamlLogicalOpType.And);
		}

		public XElement ToXml() {
			XElement whereElement = new XElement("Where");
			if (Root != null) {
				XObject elem = Root.ToXml();
				whereElement.Add(elem);
			}
			return whereElement;
		}
		/// <summary>
		/// Produces a CamlExpr from an XElement. The XElement must be a valid CAML Expression.
		/// </summary>
		/// <example>
		/// <code>
		/// const string str = @"<Where><FieldRef Name='orderby_field1' /></Where>";
		/// CamlQuery query = CamlQuery.Parse(XElement.Parse(str)); 
		/// </code>
		/// </example>
		/// <param name="element"></param>
		/// <returns></returns>
		public static CamlWhere Parse(XElement element) {
			CamlWhere result = new CamlWhere();
			int count = 0;
			foreach (XElement child in element.Elements()) {
				if (count == 0) {
					result.Root = CamlExpr.Parse(child);
				} else {
					throw new Exception("Unexpected element '" + child.Name + "'");
				}
				count++;
			}
			return result;
		}
	}
}
